"""
Author: gallopingvijay
Email: 1937832819@qq.com
Website: https://www.choudalao.com
Document:https://github.com/TencentCloud/tencentcloud-sdk-python
"""
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models
import json
import os
import yaml


def get_code(path):
    try:
        configList = get_config()
        secretId = configList['tencentcloud']['secretId']
        secretKey = configList['tencentcloud']['secretKey']
        cred = credential.Credential(
            secretId, secretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile)

        req = models.GeneralBasicOCRRequest()
        params = '{\"ImageUrl\":\"' + path + '\"}'
        req.from_json_string(params)

        resp = client.GeneralBasicOCR(req)
        res = resp.to_json_string()
        res_json = json.loads(res)
        if res_json['TextDetections'][0]['DetectedText'] is not None:
            code = res_json['TextDetections'][0]['DetectedText']
            # print(res_json['TextDetections'][0]['DetectedText'])
            return code

    except TencentCloudSDKException as err:
        print(err)


def get_config():
    '''
    获取config.yaml配置
    :return:configs
    '''
    # 获取当前文件的上级Realpath
    fileNamePath = os.path.abspath(
        os.path.dirname(os.path.dirname(__file__)))
    # 读取文件
    yamlPath = os.path.join(fileNamePath, 'config.yaml')
    # 加上 ,encoding='utf-8'，处理配置文件中含中文出现乱码的情况。
    file = open(yamlPath, 'r', encoding='utf-8')
    # 读取文件
    cont = file.read()
    # 返回配置
    return yaml.safe_load(cont)
